﻿using System;

using iTool.Cloud.DataSearch.ServiceProvider;
using iTool.Common;

using Lucene.Net.Store;

using Orleans;

namespace iTool.Cloud.DataSearch.DirectoryProvider
{
    public class iToolCloudLockFactory : LockFactory
    {
        readonly IClusterClient iCluster;
        readonly bool isLocalService;
        readonly long tableNameHash;
        public iToolCloudLockFactory(long tableNameHash, bool isLocalService)
        {
            this.isLocalService = isLocalService;
            this.iCluster = iBox.GetService<IClusterClient>("IClusterService");
            this.tableNameHash = tableNameHash;
        }

        /// <summary>
        /// 清除锁
        /// </summary>
        /// <param name="lockName"></param>
        /// <exception cref="NotImplementedException"></exception>
        public override void ClearLock(string lockName)
        {
            //Storage._locks.Remove(lockName);
            var lockService =
                this.isLocalService ? IDirectoryServiceFactory<LockService>.GetService(tableNameHash, lockName) :
                this.iCluster.GetGrain<ILockService>(this.tableNameHash, lockName);
            lockService.DisposeAsync().Wait();
        }

        /// <summary>
        /// 生成锁对象
        /// </summary>
        /// <param name="lockName"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public override Lock MakeLock(string lockName)
        {
            return new iToolCloudLock(tableNameHash,lockName, this.iCluster, this.isLocalService);
        }
    }
}
